/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 
 * 先序遍历  迭代写法
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
    let res = [],
        stack = [],
        cur =null;
    if(root)  stack.push(root)
    while (stack.length) {
        cur = stack.pop()
        res.push(cur.val)
        cur.right&&stack.push(cur.right)
        cur.left&&stack.push(cur.left)
    }
    return res
};

/**
 * 后序遍历
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function (root) {
    let res = [],
        stack = [],
        cur =null;
    if(root)  stack.push(root)
    while (stack.length) {
        cur = stack.pop()
        res.push(cur.val)
        cur.left&&stack.push(cur.left)
        cur.right&&stack.push(cur.right)
    }
    return res.reverse()
    
};


/**
 * 中序遍历
 * @param {TreeNode} root
 * @return {number[]}
 */
 var inorderTraversal = function(root, res = []) {
    const stack = [];
    let cur = root;
    while(stack.length || cur) {
        if(cur) {
            stack.push(cur);
            // 左
            cur = cur.left;
        } else {
            // --> 弹出 中
            cur = stack.pop();
            res.push(cur.val); 
            // 右
            cur = cur.right;
        }
    };
    return res;
};
